package com.zj.java21demo.exception;

import com.zj.java21demo.utils.JsonUtils;
import com.zj.java21demo.utils.ResultVoUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Description 处理认证异常和访问被拒绝
 * @Version 1.0.0
 * @Date 2024/2/28 16:48
 * @Created by zhangjun
 */
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint, AccessDeniedHandler {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
//        Result<String> result = Result.fail(401, "用户未登录或已过期");
//        response.setContentType("text/json;charset=utf-8");
//        response.getWriter().write(JsonUtil.toJson(result));


//        response.setStatus(535);
//        response.setContentType("application/json");
//        response.setCharacterEncoding("UTF-8");
//        Map<String,Object> info = new HashMap();
//        info.put("code",1001);
//        info.put("message","用户未登录或已过期");
//        response.getWriter().write(Objects.requireNonNull(JsonUtils.mapToJson(info)));
//        response.getWriter().flush();

        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JsonUtils.objectToJson(ResultVoUtil.error(1001,"用户未登录或已过期")));
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
//        Result<String> result = Result.fail(403, "权限不足");
//        response.setContentType("text/json;charset=utf-8");
//        response.getWriter().write(JsonUtil.toJson(result));
        response.setStatus(535);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        Map<String,Object> info = new HashMap();
        info.put("code",1006);
        info.put("message","权限不足");
        response.getWriter().write(Objects.requireNonNull(JsonUtils.mapToJson(info)));
        response.getWriter().flush();
    }
}
